package response

import (
	"net/http"
	"oa-system/pkg/errors"

	"github.com/gin-gonic/gin"
)

// Response 标准响应结构
type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

// PageData 分页数据结构
type PageData struct {
	List     interface{} `json:"list"`
	Total    int64       `json:"total"`
	Page     int         `json:"page"`
	PageSize int         `json:"pageSize"`
}

// NewPageData 创建分页数据
func NewPageData(list interface{}, total int64, page, pageSize int) PageData {
	return PageData{
		List:     list,
		Total:    total,
		Page:     page,
		PageSize: pageSize,
	}
}

// Success 成功响应
func Success(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, Response{
		Code:    0,
		Message: "success",
		Data:    data,
	})
}

// Error 错误响应
func Error(c *gin.Context, err error) {
	if apiErr, ok := err.(*errors.APIError); ok {
		c.JSON(apiErr.StatusCode, Response{
			Code:    apiErr.StatusCode,
			Message: apiErr.Message,
			Data:    apiErr.Err,
		})
		return
	}

	c.JSON(http.StatusInternalServerError, Response{
		Code:    http.StatusInternalServerError,
		Message: "Internal Server Error",
		Data:    err.Error(),
	})
}

// SuccessWithMessage 带消息的成功响应
func SuccessWithMessage(c *gin.Context, message string, data interface{}) {
	c.JSON(http.StatusOK, Response{
		Code:    0,
		Message: message,
		Data:    data,
	})
}

// PageSuccess 分页成功响应
func PageSuccess(c *gin.Context, list interface{}, total int64, page, pageSize int) {
	Success(c, NewPageData(list, total, page, pageSize))
}
